package com.doudou.collection.infrastructure.core.security;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.doudou.collection.dao.mapper.UserMapper;
import com.doudou.collection.dao.mapper.admin.SysUserMapper;
import com.doudou.collection.orm.entity.admin.SysUser;
import com.doudou.collection.orm.vo.UserLoginVO;
import com.doudou.collection.utils.regex.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserDetailsServiceImpl
 * @Description Security认证流程实现类
 * @Author blue sky
 * @Date 2023/6/1 23:35
 * @Version 1.0
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("启动Security认证流程");

        UserLoginVO user;
        //判断传过来的username是用户名还是邮箱或者手机号
        if (!RegexUtils.isPhoneInvalid(username)) {
            //是否为手机号
            user = userMapper.queryByPhone(username);
        } else if (!RegexUtils.isEmailInvalid(username)) {
            //是否为邮箱
            user = userMapper.queryByEmail(username);
        } else {
            //走到这一步说明是用户名
            user = userMapper.queryByUsername(username);
        }

        //如果为空，查询用户是否为管理员
        if (user == null) {
            QueryWrapper<SysUser> qw = new QueryWrapper<>();
            qw.eq("username", username);
            int count = sysUserMapper.selectCount(qw);
            if (count == 0) {
                return null;
            }
            user = sysUserMapper.getLoginInfoByUsername(username);
        }

        CustomUserDetails userDetails = new CustomUserDetails(user, getAuthority(user.getPermissions()));
        log.debug("userDetails: {}", userDetails);
        return userDetails;
    }

    private List<GrantedAuthority> getAuthority(List<String> permissions) {
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (String permission : permissions) {
            if (StrUtil.isNotEmpty(permission)) {
                GrantedAuthority authority = new SimpleGrantedAuthority(permission);
                authorities.add(authority);
            }
        }
        return authorities;
    }
}
